<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">

          <a-collapse-panel key="4" header="基础信息">
            <a-row :gutter="48">

              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep disabled :multi="false" v-model="model.proposer"/>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart disabled v-model="model.proposerDeptId"/>
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
<!--                  <j-date :disabled="true" placeholder="请选择申请时间" v-model="model.createTime" style="width: 100%"/>-->
                  <j-date
                    :disabled="formDisabled"
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        <a-collapse-panel key="1" header="往来单位信息">
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item label="企业名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enterpriseName">
              <a-input :disabled="formDisabled" v-model="model.enterpriseName" placeholder="请输入企业名称"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="商户类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="commercialType">
              <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.commercialType" dictCode="commercial_type" placeholder="请选择商户类型" @blur="commercialTypeBlur" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="企业信用代码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enterpriseCreditCode">
              <a-input :disabled="formDisabled" v-model="model.enterpriseCreditCode" placeholder="请输入企业信用代码" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="企业类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enterpriseType">
              <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.enterpriseType" dictCode="enterprise_type" placeholder="请选择企业类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="法定代表人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="legalRepresentative">
              <a-input :disabled="formDisabled" v-model="model.legalRepresentative" placeholder="请输入法定代表人"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="企业地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enterpriseAddress">
              <a-input :disabled="formDisabled" :max-length="100" v-model="model.enterpriseAddress" placeholder="请输入企业地址"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="公司注册时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="registerDate">
              <a-date-picker :disabled="formDisabled"
                  :disabled-date="disabledDate"
                  placeholder="请选择公司注册时间" v-model="model.registerDate"  style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="注册资本" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="registerCapital">
              <a-input :disabled="formDisabled" v-model="model.registerCapital" placeholder="请输入注册资本" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="8">
            <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="liaison">
              <a-input :disabled="formDisabled" v-model="model.liaison" placeholder="请输入联系人"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="liaisonMobile">
              <a-input :disabled="formDisabled"    v-model="model.liaisonMobile" placeholder="请输入联系电话" style="width: 100%" />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="8">
            <a-form-model-item label="收款账户名称" prop="bankAccountName">
              <a-input  :disabled="formDisabled" v-model="model.bankAccountName" placeholder="请输入收款账户名称" />
            </a-form-model-item>
            </a-col>
          <a-col :span="8">
              <a-form-model-item label="开户行联行号"  prop="cnapsCode">
                <SelectFinanceKingdeeBankInput :disabled="formDisabled"  v-model="model.cnapsCode"  placeholder="请选择联行号"  @back="backCnapsCode" />
              </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="开户行" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bankName">
              <a-input :disabled="formDisabled" v-model="model.bankName" placeholder="请输入收款开户行"  disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="银行账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bankAccountNo">
              <a-input :disabled="formDisabled" v-model="model.bankAccountNo" :max-length="32" placeholder="请输入银行账号"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="公司网址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="companyWeb">
              <a-input :disabled="formDisabled" :max-length="100" v-model="model.companyWeb" placeholder="请输入公司网址"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="物料大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionBroad">
              <a-select
                v-model="model.provisionBroad"
                :disabled="formDisabled"
                placeholder="请选择物料大类"
                :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="handleChange"
              >
                <a-select-option v-for="item in provisionBroadList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="物料小类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionSmall">
              <a-select
                v-model="model.provisionSmall"
                :disabled="formDisabled"
                mode="multiple"
                :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
                placeholder="请选择物料小类"
                :showArrow="true"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="provisionSmallChange"
              >
                <a-select-option v-for="item in provisionSmallList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="合作业务" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="mainBussiness">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.mainBussiness" rows="4" placeholder="请输入合作业务" />
            </a-form-model-item>
          </a-col>
        </a-row>
        </a-collapse-panel>
        <a-collapse-panel key="2" header="联系人信息">
          <erp-purchase-supplier-contact-list ref="contactList" :disabled="formDisabled"></erp-purchase-supplier-contact-list>
        </a-collapse-panel>
        <a-collapse-panel key="3" header="企业资质材料">
          <a-row :gutter="48">
          <a-col :span="6">
            <a-form-model-item label="法人身份证" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="legalRepresentativeCard">
              <!-- <j-image-upload :disabled="formDisabled" isMultiple v-model="model.legalRepresentativeCard"></j-image-upload> -->
              <j-upload  :disabled="formDisabled" v-model="model.legalRepresentativeCard"></j-upload>
<!--              <a-button v-else icon="download" @click="viewFile(model.legalRepresentativeCard)">文件列表</a-button>-->
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="营业执照" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bussinessLicense">
              <!-- <j-image-upload :disabled="formDisabled" isMultiple v-model="model.bussinessLicense"></j-image-upload> -->
              <j-upload  :disabled="formDisabled" v-model="model.bussinessLicense"></j-upload>
<!--              <a-button v-else icon="download" @click="viewFile(model.bussinessLicense)">文件列表</a-button>-->
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="供应商资质证书" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplierCertification">
              <!-- <j-image-upload :disabled="formDisabled" isMultiple v-model="model.supplierCertification"></j-image-upload> -->
              <j-upload  :disabled="formDisabled" v-model="model.supplierCertification"></j-upload>
<!--              <a-button v-else icon="download" @click="viewFile(model.supplierCertification)">文件列表</a-button>-->
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="以往合作合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cooperativeContract">
              <!-- <j-image-upload :disabled="formDisabled" isMultiple v-model="model.cooperativeContract"></j-image-upload> -->
              <j-upload  :disabled="formDisabled" v-model="model.cooperativeContract"></j-upload>
<!--              <a-button v-else icon="download" @click="viewFile(model.cooperativeContract)">文件列表</a-button>-->
            </a-form-model-item>
          </a-col>
        </a-row>
          </a-collapse-panel>
          <a-collapse-panel :hidden="!model.rejectExcuse || isEdit !== '1'" key="5" header="驳回理由">
            <a-form-model-item label="驳回理由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="rejectExcuse">
              <a-textarea :disabled="true" :max-length="500" v-model="model.rejectExcuse" rows="4" placeholder="请输入驳回理由" />
            </a-form-model-item>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
<!--      <view-file-modal ref="viewFileModal"></view-file-modal>-->
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import ErpPurchaseSupplierContactList from './reference/ErpPurchaseSupplierContactList';
  import ViewFileModal from '@/views/scy/components/ViewFileModal'
  // import { viewFile } from '@/utils/util'
  import moment from 'moment'
  import { mapGetters } from 'vuex';
  import SelectPersonInput from '@/views/scy/components/SelectPersonInput'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectFinanceKingdeeBankInput from '@/views/scy/components/SelectFinanceKingdeeBankInput'

  let urlSubmit = '/api/erp/purchase/supplier/erpPurchaseSupplier/supplierSubmit'

  export default {
    name: 'ErpPurchaseSupplierForm',
    // mixins: [viewFile],
    components: {
      ViewFileModal,
      SelectFinanceKingdeeBankInput,
      ErpPurchaseSupplierContactList,
      SelectPersonInput,
      SelectUserByDep,
      SelectTeamInput
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      isSupplier:{
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      var validatorEnterpriseName = async (rule,value,callback)=>{
        if(value){
          const that = this;
          var id = 1;
          if (this.model.id) {
            id = this.model.id
          }
          await getAction(this.url.queryByEnterpriseName, { enterpriseName: value, commercialType: this.model.commercialType, id: id  }).then(res => {
            if (res.success) {
              if(res.result == '0') {
                that.onlyEnterpriseName = false
              } else if(res.result == '1' && that.enterpriseName == value) {
                that.onlyEnterpriseName = false
              } else {
                that.onlyEnterpriseName = true
              }
            } else {
              that.$message.warning(res.message)
            }
          })
          if(that.onlyEnterpriseName) {
            callback('企业名称已存在，请重新输入！')
            return;
          }
          callback()
        }
        callback()
      };
      return {
        model:{
          commercialType: 2
        },
        labelCol: {
        },
        activeKey: ['1', '2', '3','4','5'],
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
        enterpriseName: [
            { required: true, message: '请输入企业名称!', trigger: 'blur'},
            { validator: validatorEnterpriseName, trigger: "blur" },
        ],
        commercialType: [
            { required: true, message: '请选择商户类型!', trigger: 'blur'},
        ],
        enterpriseCreditCode: [
          { validator: this.validatorEnterpriseCreditCode, trigger: "blur" }
        ],
        enterpriseType: [
            { required: true, message: '请选择企业类型!', trigger: 'blur'},
        ],
        legalRepresentative: [
            { required: true, message: '请输入法定代表人!', trigger: 'blur'},
        ],
        enterpriseAddress: [
            { required: true, message: '请输入企业地址!', trigger: 'blur'},
        ],
        registerDate: [
            { required: true, message: '请选择公司注册时间!', trigger: 'change'},
        ],
        registerCapital: [
            { required: true, message: '请输入注册资本!', trigger: 'blur'},
        ],
        // liaison: [
        //     { required: true, message: '请输入联系人!', trigger: 'blur'},
        // ],
        // liaisonMobile: [
        //     { required: true, message: '请输入联系电话!', trigger: 'blur'},
        //     { pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/, message: '请输入正确的手机号!' },
        // ],
        provisionBroad: [
            { required: true, message: '请输入物料大类!', trigger: 'blur'},
        ],
        provisionSmall: [
            { required: true, message: '请输入物料小类!', trigger: 'blur'},
        ],
        mainBussiness: [
            { required: true, message: '请输入合作业务!', trigger: 'blur'},
        ],
        bankName: [],
        bankAccountNo: [],
        bankAccountName:[],
        cnapsCode:[]
        // companyWeb: [
        //   { pattern: /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/, message: '请输入正确的网址!' },
        // ],
        },
        url: {
          add: "/api/erp/purchase/supplier/erpPurchaseSupplier/add",
          edit: "/api/erp/purchase/supplier/erpPurchaseSupplier/edit",
          queryById: "/api/erp/purchase/supplier/erpPurchaseSupplier/queryById",
          queryProvisionBroadList: "/api/erp/purchase/material/erpMaterialCategory/queryAllParent",
          queryProvisionSmallList: "/api/erp/purchase/material/erpMaterialCategory/queryChildrenByParentId",
          queryByEnterpriseCreditCode: "/api/erp/purchase/supplier/erpPurchaseSupplier/queryByEnterpriseCreditCode",
          queryByEnterpriseName: "/api/erp/purchase/supplier/erpPurchaseSupplier/queryByEnterpriseName"
        },
        provisionBroadList: [],
        provisionSmallList: [],
        provisionSmall: null,
        enterpriseCreditCode: null,
        onlyEnterpriseCreditCode: true,
        enterpriseName: null,
        onlyEnterpriseName: true,
        isEdit: ''
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      moment,
      ...mapGetters(['userInfo']),
      backCnapsCode(data){
          if(data){
            this.$set(this.model, 'bankName', data[0].bankBranchName)
          }
        },
      async validatorEnterpriseCreditCode(rule,value,callback) {
        if(value){
          const that = this;
          await getAction("/api/erp/purchase/supplier/erpPurchaseSupplier/queryByEnterpriseCreditCode", { enterpriseCreditCode: value, commercialType: this.model.commercialType }).then(res => {
            if (res.success) {
              if(res.result == '0') {
                that.onlyEnterpriseCreditCode = false
              } else if(res.result == '1' && that.enterpriseCreditCode == value) {
                that.onlyEnterpriseCreditCode = false
              } else {
                that.onlyEnterpriseCreditCode = true
              }
            } else {
              that.$message.warning(res.message)
            }
          })
          if(that.onlyEnterpriseCreditCode) {
            callback('企业信用代码已存在，请重新输入！')
            return;
          }
          callback()
        }
        callback()
      },
      commercialTypeBlur(data) {
        this.$refs["form"].clearValidate('enterpriseCreditCode');
        this.$refs["form"].clearValidate('bankName');
        this.$refs["form"].clearValidate('bankAccountNo');
        this.$refs["form"].clearValidate('bankAccountName');
        this.$refs["form"].clearValidate('cnapsCode');
        if(data == 1) {
            this.validatorRules.enterpriseCreditCode = [
              { validator: this.validatorEnterpriseCreditCode, trigger: "blur" }
            ]
            this.validatorRules.bankName = []
          //迭代16.5 银行账户字段都放开，不需要限制
            // this.validatorRules.bankAccountNo = [
            //   { pattern: /^\d{10,25}$/, message: '请输入正确的银行账号!', trigger: 'blur' }
            // ]
        } else {
          this.validatorRules.enterpriseCreditCode = [
            { required: true, message: '请输入企业信用代码!', trigger: 'blur'},
            { validator: this.validatorEnterpriseCreditCode, trigger: "blur" },
          ]
          this.validatorRules.bankAccountName = [
            { required: true, message: '请输入收款账户名称!', trigger: 'blur' },
          ]
          this.validatorRules.cnapsCode = [
            { required: true, message: '请选择开户行联行号!', trigger: 'blur' },
          ]
          this.validatorRules.bankName = [
            { required: true, message: '请输入收款开户行!', trigger: 'blur' },
          ]
          //迭代16.5 银行账户字段都放开，不需要限制
          this.validatorRules.bankAccountNo = [
            { required: true, message: '请输入银行账号!', trigger: 'blur' }
          //   { pattern: /^\d{10,25}$/, message: '请输入正确的银行账号!' },
          ]
        }
      },
      disabledDate(current) {
        return current > moment(new Date()).subtract('day')
      },
      provisionSmallChange(value) {
        this.provisionSmall = value.join(',');// 把数组项拼接成字符串，以逗号,分隔
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      findProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionBroadList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      handleChange(value) {
        this.provisionSmallList = []
        this.$set(this.model, 'provisionSmall', undefined);
        this.$refs["form"].clearValidate('provisionSmall');
        if (!!value) {
          this.findProvisionSmallList(value)
        }
      },
      findProvisionSmallList(value) {
        const that = this
        const parentId = value
        getAction(this.url.queryProvisionSmallList, { parentId }).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionSmallList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      add () {
        this.edit(this.modelDefault);
        this.userName = this.userInfo().empName;// 当前登录人名称
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.model.proposerDeptId = this.userInfo().deptId; //当前登录人部门
        this.model.proposer = this.userInfo().empId; //获取经办人id
      },
      edit (record,type) {
        this.$refs["form"].clearValidate();
        this.model = Object.assign({}, record);
        
        if(!this.formDisabled){
          this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
          this.model.proposerDeptId = this.userInfo().deptId; //当前登录人部门
          this.model.proposer = this.userInfo().empId; //获取经办人id
        }

        if (!!this.model.provisionSmall) {
          this.model.provisionSmall = this.model.provisionSmall.split(','); // 以逗号,为拆分的字符串
        } else {
          this.$set(this.model, "provisionSmall", undefined)
        }
        this.findProvisionBroadList()
        this.provisionSmallList = []
        if (!!this.model.provisionBroad) {
          this.findProvisionSmallList(this.model.provisionBroad)
        }
        if (!!this.model.enterpriseCreditCode) {
          this.enterpriseCreditCode = this.model.enterpriseCreditCode
        } else {
          this.enterpriseCreditCode = null
        }
        if (!!this.model.enterpriseName) {
          this.enterpriseName = this.model.enterpriseName
        } else {
          this.enterpriseName = null
        }
        if (this.model.id) {
          this.$refs.contactList.loadData(1, this.model.id)
        } else {
          this.$refs.contactList.dataSource = []
        }
        this.commercialTypeBlur(2)
        this.isEdit = type
        this.visible = true;
      },
      submitForm () {
        let details = this.$refs.contactList.submitForm()
        if (!details.length > 0) {
          this.$message.warning('请添加联系人信息！');
          this.$emit('unButtonDisable');
          return
        }
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            this.model.provisionSmall = this.provisionSmall
            this.model.detailList = details
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){

                if(that.isSupplier){
                  that.supplierSubmit()
                }else{
                  that.$message.success(res.message);
                  that.$emit('ok');
                }

              }else{
                that.$message.warning(res.message);
                that.$emit('unButtonDisable');
              }
            }).catch((error) => {
              that.$emit('unButtonDisable');
            }).finally(() => {
              that.confirmLoading = false;
            })
          } else {
            that.$emit('unButtonDisable');
          }
        })
      },
      async supplierSubmit(){
        if(this.isSupplier){

          if(!this.model.id){
            return this.$message.error('id不能为空')
          }

          let res = await getAction(urlSubmit,{
            id: this.model.id
          })
          
          if(res.success){
            this.$message.success(res.message||'提交成功');
            this.$emit('ok');
          }else{
            that.$message.warning(res.message)
          }
        }
      }
    }
  }
</script>
